package com.zs.backend.modules.documentManageent.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zs.backend.modules.documentManageent.dto.DocumentManagementDTO;
import com.zs.backend.modules.documentManageent.model.DocumentManagement;
import com.zs.backend.common.api.CommonPage;
import com.zs.backend.common.api.CommonResult;
import com.zs.backend.modules.documentManageent.service.DocumentManagementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.ByteArrayOutputStream;
import org.springframework.web.util.UriUtils;

/**
 * <p>
 * 文档表 前端控制器
 * </p>
 *
 * @author zs
 * @since 2024-03-18
 */
@RestController
@Api(tags = "文档管理")
@RequestMapping("/documentManageent")
public class DocumentManagementController {

    @Autowired
    private DocumentManagementService managementService;

    @ApiOperation("文档列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<DocumentManagement>> list(
        @ApiParam(value = "标题",name = "title")
        @RequestParam(value = "title", required = false) String title,

        @ApiParam(value = "创建时间-开始", name = "startCreateTime")
        @RequestParam(value = "startCreateTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startCreateTime,

        @ApiParam(value = "创建时间-结束", name = "endCreateTime")
        @RequestParam(value = "endCreateTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endCreateTime,

        @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {

        DocumentManagementDTO dto = DocumentManagementDTO.builder()
            .title(title)
            .startCreateTime(startCreateTime)
            .endCreateTime(endCreateTime)
            .build();
        Page<DocumentManagement> pageList = managementService.list(dto, pageSize,pageNum);
        return CommonResult.success(CommonPage.restPage(pageList));
    }

    @ApiOperation("添加、修改文档 (form-data 传参)")
    @RequestMapping(value = "/addOrUpt", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult addOrUpt(
        @ApiParam(value = "数据id，修改时必传",name = "id")
        @RequestParam(value = "id", required = false) Long id,
        @ApiParam(value = "标题",name = "title")
        @RequestParam(value = "title", required = false) String title,
        @ApiParam(value = "上传文件", name = "documrntFile")
        @RequestParam(value = "documrntFile", required = false) MultipartFile documrntFile) {
        DocumentManagementDTO dto = DocumentManagementDTO.builder()
            .title(title)
            .id(id)
            .documrntFile(documrntFile)
            .build();
        boolean success = managementService.addOrUpt(dto);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @ApiOperation("下载 excel 文件")
    @GetMapping("/exportExcelData/{id}")
    public ResponseEntity<byte[]> exportExcelData(
        @ApiParam(value = "数据id", name = "id")
        @PathVariable Long id) throws IOException  {

        DocumentManagement management = managementService.getFileInfo(id);
        if(management == null || management.getDocumentData() == null){
            return ResponseEntity.noContent().build();
        }
        // 从数据库获取二进制数据
        byte[] certificateData = management.getDocumentData();

        String fileName = management.getDocumentDataName();
        String encodedFileName = UriUtils.encode(fileName, StandardCharsets.UTF_8); // 编码文件名

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", encodedFileName);
        // 直接返回数据库中存储的文件内容
        return ResponseEntity.ok()
            .headers(headers)
            .body(certificateData);
    }


    @ApiOperation("删除")
    @RequestMapping(value = "/updateDel/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult updateDel(
        @ApiParam(value = "数据id", name = "id")
        @PathVariable Long id) {
        boolean success = managementService.updateDel(id);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

}

